package com.cloud.pole.weixin.wechat;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ace.cache.api.CacheAPI;
import com.alibaba.fastjson.JSONObject;
import com.cloud.pole.common.constant.CacheConstant;
import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.exception.BaseException;
import com.cloud.pole.weixin.model.entity.WxApp;
import com.cloud.pole.weixin.util.wechat.CommonRequest;
import com.cloud.pole.weixin.wechat.domain.AccessToken;
import com.cloud.pole.weixin.wechat.domain.BaseRespMsg;
import com.cloud.pole.weixin.wechat.domain.Code2SessionRespMsg;
import com.cloud.pole.weixin.wechat.domain.UserInfo;
import com.cloud.pole.weixin.wechat.http.HttpConstant;

import lombok.extern.slf4j.Slf4j;

/*
*2019年5月13日
*cloud-weixin
*author:frank-chen
*/
@Slf4j
public class CommonService {
	
	/**
	 * 获取关注用户信息
	 * @param openId
	 * @param accessToken
	 * @return
	 * @throws Exception
	 */
	public static UserInfo getSubscribeUserInfo(String openId, String accessToken) throws Exception {
		// TODO Auto-generated method stub
		String strUrl = HttpConstant.getSubscribeUserInfoURL(accessToken, openId);
		String strResult = CommonRequest.doGet(strUrl);
		log.info(strResult);
		JSONObject json = JSONObject.parseObject(strResult);
		if(json.containsKey(BaseRespMsg.ERRCODE_STR)){
			accessToken = null;
			String errcode = json.getString(BaseRespMsg.ERRCODE_STR);
			String errmsg = json.getString(BaseRespMsg.ERRMSG_STR);
			log.error("openId[" + openId + "] errcode[" + errcode + "] errmsg[" + errmsg + "]");
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, errcode + ":" + errmsg);
		}
		UserInfo userInfo = JSONObject.parseObject(strResult, UserInfo.class);
		return userInfo;
	}
	
	/**
	 * 获取AccessToken
	 * @param wxApp
	 * @return
	 * @throws Exception
	 */
	public static AccessToken getAccessToken(CacheAPI cacheAPI, String appId, String appSecret) throws Exception {
		//获取AccessToken
		String strUrl = HttpConstant.getAccessTokenURL(appId, appSecret);
		String strResult = CommonRequest.doGet(strUrl);
		JSONObject accessJson = JSONObject.parseObject(strResult);
		if(accessJson.containsKey(BaseRespMsg.ERRCODE_STR)){
			String errcode = accessJson.getString(BaseRespMsg.ERRCODE_STR);
			String errmsg = accessJson.getString(BaseRespMsg.ERRMSG_STR);
			log.error("appId[" + appId + "] errcode[" + errcode + "] errmsg[" + errmsg + "]");
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, errcode + ":" + errmsg);
		}
		AccessToken accessToken = JSONObject.parseObject(strResult, AccessToken.class);
		accessToken.setCreateTime(new Date());
		String key =  CacheConstant.SERVICE_WEIXIN_ACCESS_TOKEN_KEY + ":"  + appId;
		if(!StringUtils.isEmpty(cacheAPI.get(key))){
			cacheAPI.remove(key);
		}
		cacheAPI.set(key , accessToken, CacheConstant.SERVICE_WEIXIN_ACCESS_TOKEN_EXPIRE);
		return accessToken;
	}
	
	/**
	 * 创建菜单
	 * @param accessToken
	 * @return
	 * @throws Exception
	 */
	public static BaseRespMsg createMenu(String accessToken, String strJson) throws Exception {
		// TODO Auto-generated method stub
		String strUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
		String strResp = CommonRequest.postString(strUrl, strJson);
		BaseRespMsg respMsg = JSONObject.parseObject(strResp, BaseRespMsg.class);
		return respMsg;
	}
	
	/**
	 * 小程序：auth.code2Session
	 * @param cacheAPI
	 * @param appId
	 * @param appSecret
	 * @return
	 * @throws Exception
	 */
	public static Code2SessionRespMsg code2Session(CacheAPI cacheAPI, String appId, String appSecret, String jsCode) throws Exception {
		// TODO Auto-generated method stub
		String strUrl = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+jsCode+"&grant_type=authorization_code";
		log.info(strUrl);
		String strResp = CommonRequest.doGet(strUrl);
		log.info(strResp);
		JSONObject accessJson = JSONObject.parseObject(strResp);
		if(accessJson.containsKey(BaseRespMsg.ERRCODE_STR)){
			String errcode = accessJson.getString(BaseRespMsg.ERRCODE_STR);
			String errmsg = accessJson.getString(BaseRespMsg.ERRMSG_STR);
			log.error("appId[" + appId + "] errcode[" + errcode + "] errmsg[" + errmsg + "]");
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, errcode + ":" + errmsg);
		}
		Code2SessionRespMsg respMsg = JSONObject.parseObject(strResp, Code2SessionRespMsg.class);
		String openId = respMsg.getOpenid();
		String key =  CacheConstant.SERVICE_WEIXIN_SESSION_KEY + ":"  + openId;
		if(!StringUtils.isEmpty(cacheAPI.get(key))){
			cacheAPI.remove(key);
		}
		cacheAPI.set(key , respMsg.getSession_key(), CacheConstant.SERVICE_WEIXIN_SESSION_KEY_EXPIRE);
		return respMsg;
	}
	
	public static void main(String[] args) {
		//获取AccessToken
		String strUrl = HttpConstant.getAccessTokenURL("wxd04c995671eb1065", "b03a8891cfea8e118216cb4e33762727");
		try {
			String strResult = CommonRequest.doGet(strUrl);
			System.out.println(strResult);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
